package com.hitemole.network;

import java.io.IOException;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.List;

import com.esotericsoftware.kryonet.Client;
import com.esotericsoftware.kryonet.Connection;
import com.esotericsoftware.kryonet.Listener;
import com.hitemole.network.Network.ClientInfo;
import com.hitemole.network.Network.GameMessage;

public class ClientGame {
	public static final ClientGame clientGame = new ClientGame();
	private Client client;
	private ArrayList<GameMessage> userInput = new ArrayList<GameMessage>();
	private List<InetAddress> address;

	private ClientGame() {

	}

	public void createNewClient() {
		// TODO Auto-generated method stub
		client = new Client();
		client.start();
		Network.register(client);
		client.addListener(new Listener() {
			@Override
			public void connected(Connection arg0) {
				System.out.println("connected to server at: "
						+ arg0.getRemoteAddressTCP().getAddress());
				super.connected(arg0);
			}

			@Override
			public void received(Connection arg0, Object object) {
				// TODO Auto-generated method stub
				if (object instanceof GameMessage) {
					GameMessage gameMessage = (GameMessage) object;
					userInput.add(gameMessage);
				}
				super.received(arg0, object);
			}

			@Override
			public void disconnected(Connection arg0) {
				System.out.println("disconnect");
				super.disconnected(arg0);
			}
		});
		discoverHost();
	}

	public void discoverHost() {
		new Thread("Discover") {
			public void run() {
				address = client.discoverHosts(Network.udpPort, 3000);
				for(int i=0;i<address.size();i++){
					System.out.println(address.get(i).getAddress());
					if(address.get(i).isAnyLocalAddress() || !address.get(i).isLoopbackAddress()){
						address.remove(i);
					}
				}
			}
		}.start();
	}

	public void connectTo(final int index) {
		if (client == null)
			return;
		new Thread("Connect") {
			public void run() {
				try {
					client.connect(5000, address.get(index), Network.tcpPort);
					// Server communication after connection can go here, or in
					// Listener#connected().
				} catch (IOException ex) {
					ex.printStackTrace();
					System.exit(1);
				}
			}
		}.start();
	}

	public boolean isConnected() {
		if (client != null)
			return client.isConnected();
		return false;
	}

	public void sendToServer(GameMessage gm) {
		if (client != null)
			client.sendTCP(gm);
	}

	public void sendToServer(ClientInfo cInfo) {
		if (client != null)
			client.sendTCP(cInfo);
	}

	public void stopClient() {
		if (client != null)
			client.stop();
	}

	public ArrayList<GameMessage> getUserInput() {
		return userInput;
	}

	public int getServerList() {
		if (address != null) {
			return address.size();
		}
		return 0;
	}
}
